<?php

class MyMVC {
    /**
     * 控制器
     * @var string
     */
    private $c;
    /**
     * Action
     * @var string
     */
    private $a;
    /**
     * 单例
     * @var MyMVC
     */
    private static $_instance;
    /**
     * 构造函数，初始化配置
     * @param array $conf
     */
    private function __construct($conf){
        C($conf);
    }
    private function __clone(){}
    /**
     * 获取单例
     * @param array $conf
     * @return MyMVC
     */
    public static function getInstance($conf){
        if(!(self::$_instance instanceof self)){
            self::$_instance = new self($conf);
        }
        return self::$_instance;
    }
    /**
     * 运行应用实例
     * @access public
     * @return void
     */
    public function run(){
        if(C('USE_SESSION') == true){
            session_start();
        }
        //加载项目公共函数
        includeIfExist( COMMON_PATH.'function.php');
        $pathMod = C('PATH_MOD');
        $pathMod = empty($pathMod)?'NORMAL':$pathMod;
        //自动加载。
        spl_autoload_register(array('MyMVC', 'autoload'));
        if(strcmp(strtoupper($pathMod),'NORMAL') === 0 || !isset($_SERVER['PATH_INFO'])){
            $this->c = isset($_GET['c'])?$_GET['c']:'Index';
            $this->a = isset($_GET['a'])?$_GET['a']:'Index';
        }else{
            $pathInfo = isset($_SERVER['PATH_INFO'])?$_SERVER['PATH_INFO']:'';
            $pathInfoArr = explode('/',trim($pathInfo,'/'));
            if(isset($pathInfoArr[0]) && $pathInfoArr[0] !== ''){
                $this->c = $pathInfoArr[0];
            }else{
                $this->c = 'Index';
            }
            if(isset($pathInfoArr[1])){
                $this->a = $pathInfoArr[1];
            }else{
                $this->a = 'Index';
            }
        }
        if(!class_exists($this->c.'Controller')){
            halt('控制器'.$this->c.'不存在');
        }
        $controllerClass = $this->c.'Controller';
        $controller = new $controllerClass();
        if(!method_exists($controller, $this->a.'Action')){
            halt('方法'.$this->a.'不存在');
        }
        call_user_func(array($controller,$this->a.'Action'));
    }
    /**
     * 自动加载函数
     * @param string $class 类名
     */
    public static function autoload($class){
        //在这里加入框架的类试试
        includeIfExist(LIB_PATH.$class.'.php');
        if(substr($class,-10)=='Controller'){
            includeIfExist(APP_PATH.'Controller/'.$class.'.class.php');
        }elseif(substr($class,-6)=='Widget'){
            includeIfExist(APP_PATH.'Widget/'.$class.'.class.php');
        }else{
            //这里如果加载框架的类，那程序的肿么办？
            includeIfExist(APP_PATH.'Lib/'.$class.'.class.php');
        }
    }
}


?>